package com.ledou44.apollolearn.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @author caoxiaoyang
 * 监听springboot 启动完成
 */
@Component
@Log
public class ApolloConfig implements ApplicationListener<ApplicationStartedEvent> {

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        //监听数据库连接池信息变化 并重新加载连接池信息
        Config config = ConfigService.getConfig("datasource");
        config.addChangeListener(event -> {
            DruidDataSource dataSource = (DruidDataSource) applicationContext.getBean("dataSource");
            for (String changedKey : event.changedKeys()) {
                if(changedKey.equals("db.url")) {
                    dataSource.setUrl(event.getChange(changedKey).getNewValue());
                } else if(changedKey.equals("db.username")) {
                    dataSource.setUsername(event.getChange(changedKey).getNewValue());
                } else if(changedKey.equals("db.password")) {
                    dataSource.setPassword(event.getChange(changedKey).getNewValue());
                }
            }
            try {
                dataSource.restart();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
    }
}
